import dayjs from 'dayjs'
import relativeTime from 'dayjs/plugin/relativeTime'
import duration from 'dayjs/plugin/duration'

dayjs.extend(relativeTime)
dayjs.extend(duration)

/**
 * 格式化日期时间
 */
export const formatDateTime = (date: Date | string, format = 'YYYY-MM-DD HH:mm:ss'): string => {
  return dayjs(date).format(format)
}

/**
 * 相对时间
 */
export const timeAgo = (date: Date | string): string => {
  return dayjs(date).fromNow()
}

/**
 * 格式化文件大小
 */
export const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i]
}

/**
 * 防抖函数
 */
export const debounce = <T extends (...args: any[]) => any>(
  func: T,
  wait: number
): ((...args: Parameters<T>) => void) => {
  let timeout: ReturnType<typeof setTimeout> | null = null

  return function executedFunction(...args: Parameters<T>) {
    const later = () => {
      timeout = null
      func(...args)
    }

    if (timeout) {
      clearTimeout(timeout)
    }
    timeout = setTimeout(later, wait)
  }
}

/**
 * 节流函数
 */
export const throttle = <T extends (...args: any[]) => any>(
  func: T,
  limit: number
): ((...args: Parameters<T>) => void) => {
  let inThrottle: boolean

  return function executedFunction(...args: Parameters<T>) {
    if (!inThrottle) {
      func(...args)
      inThrottle = true
      setTimeout(() => (inThrottle = false), limit)
    }
  }
}

/**
 * 深拷贝
 */
export const deepClone = <T>(obj: T): T => {
  return JSON.parse(JSON.stringify(obj))
}

/**
 * 生成唯一ID
 */
export const generateId = (): string => {
  return Date.now().toString(36) + Math.random().toString(36).substr(2)
}

/**
 * 下载文件
 */
export const downloadFile = (url: string, filename: string): void => {
  const link = document.createElement('a')
  link.href = url
  link.download = filename
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

/**
 * 复制到剪贴板
 */
export const copyToClipboard = async (text: string): Promise<boolean> => {
  try {
    await navigator.clipboard.writeText(text)
    return true
  } catch (err) {
    console.error('Failed to copy:', err)
    return false
  }
}

/**
 * 获取严重程度颜色
 */
export const getSeverityColor = (severity: string): string => {
  const colors: Record<string, string> = {
    critical: '#ff4d4f',
    high: '#ff7a45',
    medium: '#ffa940',
    low: '#52c41a',
  }
  return colors[severity] || '#d9d9d9'
}

/**
 * 获取状态颜色
 */
export const getStatusColor = (status: string): string => {
  const colors: Record<string, string> = {
    firing: '#ff4d4f',
    resolved: '#52c41a',
    acknowledged: '#1890ff',
    created: '#faad14',
    assigned: '#1890ff',
    in_progress: '#13c2c2',
    pending: '#fa8c16',
    closed: '#8c8c8c',
  }
  return colors[status] || '#d9d9d9'
}

/**
 * 计算时间差（分钟）
 */
export const getTimeDiffInMinutes = (start: Date | string, end: Date | string = new Date()): number => {
  return dayjs(end).diff(dayjs(start), 'minute')
}

/**
 * 格式化持续时间
 */
export const formatDuration = (minutes: number): string => {
  const duration = dayjs.duration(minutes, 'minutes')

  if (duration.asDays() >= 1) {
    return `${Math.floor(duration.asDays())}天${duration.hours()}小时`
  } else if (duration.asHours() >= 1) {
    return `${Math.floor(duration.asHours())}小时${duration.minutes()}分钟`
  } else {
    return `${duration.minutes()}分钟`
  }
}

/**
 * 截断文本
 */
export const truncate = (text: string, maxLength: number): string => {
  if (text.length <= maxLength) return text
  return text.substring(0, maxLength) + '...'
}

/**
 * 高亮搜索文本
 */
export const highlightText = (text: string, search: string): string => {
  if (!search) return text
  const regex = new RegExp(`(${search})`, 'gi')
  return text.replace(regex, '<mark>$1</mark>')
}
